package com.cg.utils;

import java.util.HashMap;
import java.util.Map;

import com.cg.entity.ShortMessage;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jsms.api.JSMSClient;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.ValidSMSResult;
import cn.jsms.api.common.SMSClient;
import cn.jsms.api.common.model.SMSPayload;

/**
 * 推送
 * @author cumt
 *
 */
public class JpushUtil {
	
	public static final String MSG_CONTENT = "Test from API Example - msgContent";
    public static final String ALERT = "Test from API Example - alert";
//    protected static final String APP_KEY ="727d1643b094bec1b1f1ce08";
//    protected static final String MASTER_SECRET = "8951f6038d164afea668ae28";
    
    public static final String APP_KEY ="49544912f0354f89e43301da";
    public static final String MASTER_SECRET = "d795f6a5aed51e9f5be1fdd9";
    	
    public static void SendPush() {
    	ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
        // Call setHttpClient to set httpClient,
        // If you don't invoke this method, default httpClient will use NativeHttpClient.
//        ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
//        jpushClient.getPushClient().setHttpClient(httpClient);
//        final PushPayload payload = buildPushObject_all_all_alert("1230");
//        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObject_android_tag_alertWithTitle("18580568258","123","123");
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println(result);
            // 如果使用 NettyHttpClient，需要手动调用 close 方法退出进程
            // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
            // jpushClient.close();
        } catch (APIConnectionException e) {

        } catch (APIRequestException e) {
        }
    	
    	
    }
    
    
    /**
     * 	推送给某个人（手机号推送）
     * @return
     */
    public static void sendPushToSomeOne(String phone,String content,String title) {
    	ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        PushPayload payload = buildPushObject_android_tag_alertWithTitle(phone,content,title);
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println(result);
        } catch (APIConnectionException e) {

        } catch (APIRequestException e) {
        }
    	
    }
    /**
     * 	推送给某个人（手机号推送）
     * @return
     */
    public static PushPayload buildPushObject_android_tag_alertWithTitle(String phone,String content ,String title) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.tag(phone))
                .setNotification(Notification.android(content, title, null))
                .build();
    }
    /**
     * 推送给某个人（手机号推送）
     * @return
     */
    public static PushPayload buildPushObject_all_alias_alert(String phone,String content) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(phone))
                .setNotification(Notification.alert(content))
                .build();
    }
    
    /**
     * 推送给全部
     * @return
     */
    public static PushPayload buildPushObject_all_all_alert(String content) {
    	PushPayload pushPayload = PushPayload.alertAll(content);
    	pushPayload.resetOptionsApnsProduction(true);
        return pushPayload;
    }
    
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag("13983441921", "tag2"))
                        .addAudienceTarget(AudienceTarget.alias("13983441921", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(MSG_CONTENT)
                        .addExtra("from", "JPush")
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }
    /**
	 * 推送 content:内容,ailas：别名 user+用户id
	 * 
	 * @param content
	 * @param type
	 *            :1、宣讲会推送；2、面试邀请推送
	 * @return
	 */
	public static void push(String content, String pushobject, String tag, String type)
			throws Exception {
		String message_ios = "{\"msg\":\"发送失败\"}";
		String message_android = "{\"msg\":\"发送失败\"}";
		String message_ios_android = "{\"msg\":\"发送失败\"}";
		// String masterSecret = "477b1cd6ee20ff44abedd876";
//		String masterSecret = "031f3b5d3241b90738647e15";
//		String appKey = "70bc386d09cadb081e51c5a1";
		// String[] pushobjects = pushobject.split(",");
		JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, 3);
		PushPayload payload_ios = null;
		PushPayload payload_android = null;
		PushPayload payload_ios_android = null;
		// payload = buildPushObject_all_alias_alert(content, ailas);//
		// ios和安卓使用别名推送，不需要判断
		if ("1".equals(type)) {// 宣讲会推送
			payload_ios = buildPushObject_ios_tag_alertWithTitle(content, tag);// ios和安卓使用标记推送，不需要判断
//			payload_android = buildPushObject_android_tag_alertWithTitle(
//					content, tag);
		} else if ("2".equals(type)) {// 面试邀请推送
			payload_ios_android = buildPushObject_all_alias_alert(content, tag);// ios和安卓使用标记推送，不需要判断
		}
		// payload = buildPushObject_all_all_alert(content);
		// if (pushobjects.length > 1) {
		// payload = buildPushObject_all_all_alert(content);
		// } else {
		// if (!"".equals(ailas)) {
		// payload = buildPushObject_all_alias_alert_platform_alias(
		// content, pushobjects[0], ailas);
		// } else {
		// payload = buildPushObject_all_alias_alert_platform(content,
		// pushobjects[0]);
		// }
		// }
		try {
			if ("1".equals(type)) {
				PushResult result_ios = jpushClient.sendPush(payload_ios);
				if (result_ios.isResultOK()) {
					message_ios = "{\"msg\":\"发送成功\"}";
				}
				PushResult result_android = jpushClient
						.sendPush(payload_android);
				if (result_android.isResultOK()) {
					message_android = "{\"msg\":\"发送成功\"}";
				}
			} else {
				PushResult result_ios_android = jpushClient
						.sendPush(payload_ios_android);
				if (result_ios_android.isResultOK()) {
					message_ios_android = "{\"msg\":\"发送成功\"}";
				}
			}
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
	}
    
	// 构建推送对象：平台是 ios，目标是 tag 为 "tag1" 的设备，内容是 Android 通知 ALERT，并且标题为 TITLE。
	public static PushPayload buildPushObject_ios_tag_alertWithTitle(
			String content, String tag) {
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.ios())
				.setAudience(Audience.tag(tag))
				.setNotification(
						Notification
								.newBuilder()
								.addPlatformNotification(
										IosNotification.newBuilder()
												.setAlert(content)
												.setSound("happy.caf").build())
								.build()).build();
	}
	
    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     * @param alias
     * @param alert
     * @return PushPayload
     */
    public static PushPayload buildPushObject_android_ios_alias_alert(String alias,String alert){
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtra("type", "infomation")
                                .setAlert(alert)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("type", "infomation")
                                .setAlert(alert)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }
    
    /**
     * 推送给全部
     * @return
     */
    public static PushPayload buildPushObject_android_and_ios() {
        Map<String, String> extras = new HashMap<String, String>();
        extras.put("test", "https://community.jiguang.cn/push");
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.tag("13983441921"))  
                .setNotification(Notification.newBuilder()
                		.setAlert("alert content")
                		.addPlatformNotification(AndroidNotification.newBuilder()
                				.setTitle("Android Title")
                                .addExtras(extras).build())
                		.addPlatformNotification(IosNotification.newBuilder()
                				.incrBadge(1)
                				.addExtra("extra_key", "extra_value").build())
                		.build())
                .build();
    }
    
    
    
    /**
     * 发送验证码
     * @param message
     * @param code
     * @return
     */
    public static SendSMSResult sendCode(ShortMessage message,String code) {
    	
    	SMSClient client = new SMSClient(MASTER_SECRET, APP_KEY);
    	SMSPayload payload = SMSPayload.newBuilder()
				.setMobileNumber(message.getPhone())
				.setCode(code)
				.setTempId(1)
				.build();
    	try {
			SendSMSResult res = client.sendSMSCode(payload);
            System.out.println(res.toString());
            //插入数据到表
            if(res!=null && !"".equals(res.getMessageId())) {
                
            }
            else {
//            	return AppUtil.returnFail("发送失败");
            }
            
            return res;
        	
		} catch (APIConnectionException e) {
//			return AppUtil.returnFail("发送失败");
			return null;
        } catch (APIRequestException e) {
//        	return AppUtil.returnFail("发送失败");
        	return null;
        }
    	
    }
    
    /**
     * 验证短信验证码
     * @param message
     * @param code
     * @return
     */
    public static ValidSMSResult validCode(ShortMessage message ) {
    	JSMSClient client = new JSMSClient(MASTER_SECRET, APP_KEY);
    	try {
//			SendSMSResult res = client.sendSMSCode(payload);
//            System.out.println(res.toString());
    		ValidSMSResult res = client.sendValidSMSCode(message.getPhone(),message.getCode());
            return res;
        	
		} catch (APIConnectionException e) {
//			return AppUtil.returnFail("发送失败");
			return null;
        } catch (APIRequestException e) {
//        	return AppUtil.returnFail("发送失败");
        	return null;
        }
    	
    }
}
